package net.esj.basic.core.view.filter;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esj.basic.core.engine.config.MelonConfig;
import net.esj.basic.utils.ImageUtils;
import net.esj.basic.utils.StringUtils;
import net.esj.basic.utils.Validators;
import net.esj.basic.core.utils.PropertiesInfo;

public class ImageCompressFilter implements Filter {

	private String imageTypes =".jpg,.jpeg,.bmp,.png";
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		String url = req.getRequestURI();
		if(checkIsImage(url)){
			String wStr =  req.getParameter("w");
			String hStr = req.getParameter("h");
			if(!StringUtils.hasText(wStr) && !StringUtils.hasText(hStr)){
				arg2.doFilter(arg0, arg1);
				return;
			}
			int width = 0;
			int height = 0;
			if(StringUtils.hasText(wStr)){
				width = Integer.valueOf(wStr);
			}
			if(StringUtils.hasText(hStr)){
				height = Integer.valueOf(hStr);
			}
			String filename = url.substring(url.lastIndexOf("/")+1);
			String baseDir = MelonConfig
					.getProperty(PropertiesInfo.MELON_PROP_SYS_UPLOAD_ROOT);
			String baseUrl = MelonConfig.getProperty(PropertiesInfo.MELON_PROP_SYS_DOWNLOAD_URL);
//			String relative= req.getRequestURL().toString().replace(baseUrl, "");
			String relative = "";
			if(!Validators.isEmpty(baseUrl)){
				String[] baseUrls = baseUrl.split("/");
				String baseUrlLast = baseUrls[baseUrls.length-1];
				String reqUrl = req.getRequestURL().toString();
				String[] reqUrls = reqUrl.split(baseUrlLast);
				relative = reqUrls[reqUrls.length-1];
			}
			relative = relative.replaceAll("/",Matcher.quoteReplacement(File.separator));
			if(!baseDir.endsWith(File.separator)){
				baseDir += File.separator;
			}
			File image = new File(baseDir+relative);
			String newName = ImageUtils.compressImage(image, width, height);
			
			url = url.replace(filename, newName);
			resp.sendRedirect(url);
		}else{
			arg2.doFilter(arg0, arg1);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		String types = arg0.getInitParameter("imageTypes");
		if(StringUtils.hasText(types)){
			imageTypes = types;
		}
	}

	private boolean checkIsImage(String url){
		for(String str : imageTypes.split(",")){
			if(StringUtils.endsWithIgnoreCase(url, str)){
				return true;
			}
		}
		return false;
	}
}
